import React, { useState, useEffect } from 'react';
import { CheckCard } from '@ant-design/pro-components';
import { Divider, Popconfirm, Select, Tabs, Col, Row } from 'antd';
import './index.less';

import { v4 as uuidv4 } from 'uuid';

type DefaultValuesType = string | number | boolean | undefined;

interface DrugModalProps {
  height: number
  list: any[] | undefined;
  multiple: boolean;
  detaultValues: DefaultValuesType | DefaultValuesType[]
  onChange: any
}



const DrugModal: React.FC<DrugModalProps> = ({
  height,
  list,
  multiple,
  detaultValues,
  onChange = () => { },
}) => {
  const [openPopconfirms, setOpenPopconfirms] = useState<{ [key: string]: boolean }>({});
  const [filteredList, setFilteredList] = useState<any[]>([]);
  const [commonanyList, setCommonanyList] = useState<any[]>([]);
  // const [selectedItems, setSelectedItems] = useState<any[]>([]);
  const [searchList, setSearchList] = useState(null as any);

  const [checkList, setCheckList] = useState(null as any)

  const handleDefaultValues = (detaultValues: any) => {
    if (Array.isArray(detaultValues) && detaultValues.length > 0) {
      const resultArray = detaultValues.flatMap(item => item?.split(','));
      console.log('resultArray', resultArray);

      setCheckList(resultArray);
    } else {
      setCheckList(Array.isArray(detaultValues) ? [] : detaultValues || []);
    }
  };

  // 初始化过滤数组
  const fetchData = async () => {
    if (list) {
      //  外部传递 detaultValues 
      // const detaultValues = await formRef.getFieldValue();
      handleDefaultValues(detaultValues);

      // 初始化常用病状列表
      const initialCommonanys = (list || [])?.reduce((acc: any[], parent: any) => {
        const commonChildren = (parent?.children || parent?.child || [])?.filter((child: any) => child?.checked);
        return [...acc, ...commonChildren];
      }, []);

      console.log('initialCommonanys', initialCommonanys);
      setCommonanyList(initialCommonanys);

      // 检查 detaultValues 是否为数组
      const detaultValuesArray = Array.isArray(detaultValues) ? detaultValues : detaultValues?.split(',');
      console.log('detaultValuesArray', detaultValuesArray)
      // 初始化过滤后的列表，并添加 checked 属性
      const updatedFilteredList = list?.map((parent: any) => ({
        name: parent?.name,
        id: parent?.id || uuidv4(),  // 保留已有 id，否则生成新的 UUID
        children: (parent?.children || parent?.child)?.map((child: any) => {
          const isChecked = detaultValuesArray?.includes(child?.name);
          // console.log('child', detaultValuesArray, child, isChecked);
          return {
            ...child,
            checked: isChecked,
          };
        }),
      }));
      console.log('updatedFilteredList', list, updatedFilteredList);
      setFilteredList(updatedFilteredList);
    }
  };

  // 处理打开和关闭 Popconfirm 的状态
  const handleOpenChange = (isOpen: boolean, itemName: string) => {
    setOpenPopconfirms((prev) => ({
      ...Object.keys(prev)?.reduce((acc, key) => {
        acc[key] = false;
        return acc;
      }, {} as { [key: string]: boolean }),
      [itemName]: isOpen,
    }));
  };

  // 添加常用病状
  const addCommonany = (subitem: any) => {
    setCommonanyList((prevList) => {
      if (!prevList.some((item) => item?.name === subitem?.name)) {
        return [...prevList, subitem];
      }
      return prevList;
    });
  };

  // 移除常用病状
  const removeCommonany = (subitem: any) => {
    console.log('subitem', subitem);

    setCommonanyList((prevList) => prevList.filter((item) => item?.name !== subitem?.name));
  };

  // 处理 CheckCard 的选中状态变化
  const handleCardChange = (checked: boolean, item: any) => {
    console.log('handleCardChange', item, checked);

    // 更新列表，处理多选和单选模式
    const updatedList = filteredList.map(parent => ({
      ...parent,
      children: parent.children.map(child => {
        if (multiple) {
          return child?.name === item.name ? { ...child, checked } : child;
        } else {
          return { ...child, checked: child?.name === item?.name ? checked : false };
        }
      }),
    }));

    // 过滤出 checked 为 true 的字段
    const filterCheckedItems = (list: any[]): { result: string[], checkedItems: string[] } => {
      const result: any[] = [];
      const checkedItems: string[] = [];
      list.forEach(parent => {
        if (parent.children) {
          parent.children
            .filter(child => child.checked)
            .forEach(child => {
              result.push(child);
              checkedItems.push(child.name);
            });
        }
      });
      return { result, checkedItems };
    };

    const { result, checkedItems } = filterCheckedItems(updatedList);
    setFilteredList(updatedList)
    onChange(result)
    console.log('filterCheckedItems(updatedList)', result, checkedItems);
    // 更新过滤后的列表
    if (multiple) {
      // setSelectedItems(checkedItems);
      setCheckList(checkedItems);
    } else {
      // 单选模式
      // setSelectedItems(item.name); // 设置选中项为当前项
      setCheckList(item?.name);
    }
  };

  // 根据搜索关键字更新过滤后的列表
  const handleSearch = (keyword: string) => {
    let result: any = [];
    if (keyword.length > 0) {
      list?.forEach((parent: any) => {
        if (parent?.children && parent?.children.length > 0) {
          parent.children.forEach((child: any) => {
            if (child?.name.includes(keyword)) {
              result.push(child);
            }
          });
        }
      });
    }
    // console.log('extractChildren(result)', extractChildren(result));
    setSearchList(extractChildren(result));
  };

  // 提取子项的名称作为 AutoComplete 的选项
  const extractChildren = (data: any[]) => {
    return data.map((child) => ({
      value: child.name,
      label: child.name,
    }));
  };

  const handleSelect = (params: string | number) => {
    if (multiple) {
      // setSelectedItems((pre) => [...pre, params])
      // handleCardChange(true, params)
      setCheckList((pre: [string | number]) => [...pre, params])
    } else {
      // setSelectedItems(params)
      // handleCardChange(true, params)
      setCheckList(params)
    }
  }


  //tab 
  const handleTabChange = (key) => {

    console.log('handleTabChange', key);

    const anchorElement = document.getElementById(key);

    console.log('anchorElement', anchorElement);

    if (anchorElement) {
      anchorElement.scrollIntoView({ behavior: 'smooth' });
    }
  }

  // 初始化常用病状列表和过滤后的列表
  useEffect(() => {
    fetchData();
  }, [list]);

  // 处理默认值
  useEffect(() => {
    handleDefaultValues(detaultValues);
  }, [detaultValues]);

  return (
    <Row>
      <Col span={6} >
        <Tabs tabPosition='left' type='card' style={{ height: `${height + 2}vh` }} onChange={handleTabChange}>
          {
            filteredList?.map((item, index) => {
              return <Tabs.TabPane
                key={item?.id}
                tabKey={item?.id}
                tab={
                  <div className='drug-tabs-item'>{item?.name}</div>
                }
              />
            })
          }
        </Tabs>
      </Col>

      <Col span={18} style={{ height: `${height}vh`, padding: '8px', overflow: 'auto' }}>
        <>
          <Select
            value={checkList}
            showSearch={true}
            mode={multiple ? 'multiple' : undefined}
            style={{ width: '100%' }}
            options={searchList}
            onSearch={(value: string) => handleSearch(value)}
            onSelect={(value: string) => handleSelect(value)}
            onDeselect={(value: string) => removeCommonany(value)}
            autoFocus={true}
            placeholder="请输入关键字搜索"
          />
          {/* 病状 */}
          {/* <Divider style={{ fontWeight: 'bold', textAlign: 'center', marginBottom: '20px' }} /> */}
          <CheckCard.Group multiple={multiple} value={checkList}>
            {/* 常用病状 */}
            <Divider style={{ fontWeight: 'bold', textAlign: 'center', marginBottom: '20px' }}>
              常用病状
            </Divider>
            {commonanyList?.map((item: any) => (
              <Popconfirm
                key={item.id}
                title="是否移除常用项目？"
                okText="是"
                cancelText="否"
                onConfirm={() => removeCommonany(item)}
              >
                <CheckCard
                  key={item.id}
                  className='check-card'
                  title={item.name}
                  value={item.name}
                  // checked={item.checked} // 动态设置选中状态
                  onChange={(checked) => handleCardChange(checked, item)}
                />
              </Popconfirm>

            ))}
            {filteredList?.map((parent: any) => (
              <div key={parent.id}>
                <Divider
                  style={{ fontWeight: 'bold', textAlign: 'center', marginBottom: '20px' }}
                >
                  <div id={parent?.id}>{parent?.name}</div>
                </Divider>
                <div>
                  {parent.children?.map((subitem: any) => (
                    <Popconfirm
                      key={subitem.id}
                      title="是否添加到常用项"
                      okText="是"
                      cancelText="否"
                      open={openPopconfirms[subitem.name] || false}
                      onConfirm={() => {
                        addCommonany(subitem);
                        handleOpenChange(false, subitem.name);
                      }}
                      onCancel={() => handleOpenChange(false, subitem.name)}
                    >
                      <span
                        className="check-card-span"
                        onDoubleClick={() => handleOpenChange(true, subitem.name)}
                      >
                        <CheckCard
                          key={subitem.id}
                          className="check-card"
                          title={subitem.name}
                          value={subitem.name}
                          checked={subitem.checked} // 动态设置选中状态
                          // defaultChecked
                          onChange={(checked) => handleCardChange(checked, subitem)}
                        />
                      </span>
                    </Popconfirm>
                  ))}
                </div>
              </div>
            ))}
          </CheckCard.Group >
        </>
      </Col>
    </Row>
  );
};

export default React.memo(DrugModal);
